package com.example.managemyself.ui.settings;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.managemyself.R;
import com.example.managemyself.data.model.User;
import com.example.managemyself.model.UserSettings;
import com.example.managemyself.util.SettingsManager;
import com.example.managemyself.util.UserManager;
import com.example.managemyself.viewmodel.ProfileViewModel;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText;

/**
 * 设置页面Fragment
 */
public class SettingsFragment extends Fragment {

    private ProfileViewModel viewModel;
    private SwitchMaterial switchNotifications;
    private SwitchMaterial switchDataSync;
    private SwitchMaterial switchBiometric;
    private SeekBar seekBarPomodoroWork;
    private SeekBar seekBarPomodoroBreak;
    private TextView tvPomodoroWork;
    private TextView tvPomodoroBreak;
    private Spinner spinnerTheme;
    private Spinner spinnerSyncFrequency;
    private Spinner spinnerDataRetention;
    private Spinner spinnerAutoLock;
    private TextInputEditText etWeatherApiKey;
    private TextInputEditText etAiApiKey;
    private TextInputEditText etAlmanacApiKey;
    private Button btnTestWeatherApi;
    private Button btnTestAiApi;
    private Button btnTestAlmanacApi;
    private Button btnSaveSettings;
    private Button btnResetSettings;
    private Button btnClearData;

    private UserSettings currentSettings;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_settings, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initViews(view);
        setupViewModels();
        setupSpinners();
        setupSeekBars();
        setupClickListeners();
        loadCurrentSettings();
    }

    private void initViews(View view) {
        switchNotifications = view.findViewById(R.id.switch_notifications);
        switchDataSync = view.findViewById(R.id.switch_data_sync);
        switchBiometric = view.findViewById(R.id.switch_biometric);
        seekBarPomodoroWork = view.findViewById(R.id.seekbar_pomodoro_work);
        seekBarPomodoroBreak = view.findViewById(R.id.seekbar_pomodoro_break);
        tvPomodoroWork = view.findViewById(R.id.tv_pomodoro_work);
        tvPomodoroBreak = view.findViewById(R.id.tv_pomodoro_break);
        spinnerTheme = view.findViewById(R.id.spinner_theme);
        spinnerSyncFrequency = view.findViewById(R.id.spinner_sync_frequency);
        spinnerDataRetention = view.findViewById(R.id.spinner_data_retention);
        spinnerAutoLock = view.findViewById(R.id.spinner_auto_lock);
        etWeatherApiKey = view.findViewById(R.id.et_weather_api_key);
        etAiApiKey = view.findViewById(R.id.et_ai_api_key);
        etAlmanacApiKey = view.findViewById(R.id.et_almanac_api_key);
        btnTestWeatherApi = view.findViewById(R.id.btn_test_weather_api);
        btnTestAiApi = view.findViewById(R.id.btn_test_ai_api);
        btnTestAlmanacApi = view.findViewById(R.id.btn_test_almanac_api);
        btnSaveSettings = view.findViewById(R.id.btn_save_settings);
        btnResetSettings = view.findViewById(R.id.btn_reset_settings);
        btnClearData = view.findViewById(R.id.btn_clear_data);
    }

    private void setupViewModels() {
        viewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
    }

    private void setupSpinners() {
        // 主题选择器
        String[] themes = {"浅色主题", "深色主题", "跟随系统"};
        ArrayAdapter<String> themeAdapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, themes);
        themeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTheme.setAdapter(themeAdapter);

        // 同步频率选择器
        String[] frequencies = {"从不", "每日", "每周", "每月"};
        ArrayAdapter<String> frequencyAdapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, frequencies);
        frequencyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerSyncFrequency.setAdapter(frequencyAdapter);

        // 数据保留时间选择器
        String[] retentions = {"1个月", "3个月", "6个月", "1年", "永久"};
        ArrayAdapter<String> retentionAdapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, retentions);
        retentionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerDataRetention.setAdapter(retentionAdapter);

        // 自动锁定时间选择器
        String[] lockTimes = {"立即", "1分钟", "5分钟", "15分钟", "30分钟", "从不"};
        ArrayAdapter<String> lockAdapter = new ArrayAdapter<>(requireContext(),
                android.R.layout.simple_spinner_item, lockTimes);
        lockAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerAutoLock.setAdapter(lockAdapter);
    }

    private void setupSeekBars() {
        // 番茄钟工作时长设置（5-60分钟范围，通过偏移实现）
        seekBarPomodoroWork.setMax(55); // 最大55（5-60分钟范围）
        seekBarPomodoroWork.setProgress(20); // 默认25分钟（20+5=25）
        tvPomodoroWork.setText("25分钟");

        seekBarPomodoroWork.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int actualValue = progress + 5; // 加上偏移量
                    tvPomodoroWork.setText(actualValue + "分钟");
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        // 番茄钟休息时长设置（1-30分钟范围）
        seekBarPomodoroBreak.setMax(29); // 最大29（1-30分钟范围）
        seekBarPomodoroBreak.setProgress(4); // 默认5分钟（4+1=5）
        tvPomodoroBreak.setText("5分钟");

        seekBarPomodoroBreak.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int actualValue = progress + 1; // 加上偏移量
                    tvPomodoroBreak.setText(actualValue + "分钟");
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }

    private void setupClickListeners() {
        btnSaveSettings.setOnClickListener(v -> saveSettings());
        btnResetSettings.setOnClickListener(v -> confirmResetSettings());
        btnClearData.setOnClickListener(v -> confirmClearData());
        
        // API测试按钮
        btnTestWeatherApi.setOnClickListener(v -> testWeatherApi());
        btnTestAiApi.setOnClickListener(v -> testAiApi());
        btnTestAlmanacApi.setOnClickListener(v -> testAlmanacApi());
        
        // 主题切换监听器
        spinnerTheme.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long id) {
                applyThemeChange(position);
            }
            
            @Override
            public void onNothingSelected(android.widget.AdapterView<?> parent) {}
        });
    }

    private void applyThemeChange(int themePosition) {
        // 防止初始化时触发
        if (currentSettings == null) {
            return;
        }
        
        com.example.managemyself.util.ThemeManager themeManager = 
            com.example.managemyself.util.ThemeManager.getInstance(requireContext());
        
        switch (themePosition) {
            case 0: // 浅色主题
                themeManager.setThemeMode(com.example.managemyself.util.ThemeManager.THEME_LIGHT);
                break;
            case 1: // 深色主题
                themeManager.setThemeMode(com.example.managemyself.util.ThemeManager.THEME_DARK);
                break;
            case 2: // 跟随系统
                themeManager.setThemeMode(com.example.managemyself.util.ThemeManager.THEME_SYSTEM);
                break;
        }
        
        // 立即重新创建Activity以应用主题
        if (getActivity() != null) {
            getActivity().recreate();
        }
    }

    private void loadCurrentSettings() {
        User currentUser = UserManager.getInstance().getCurrentUser();
        if (currentUser != null) {
            viewModel.getUserSettings(currentUser.getId()).observe(getViewLifecycleOwner(), settings -> {
                if (settings != null) {
                    currentSettings = settings;
                    updateUIWithSettings(settings);
        } else {
                    // 创建默认设置
                    currentSettings = new UserSettings(currentUser.getId());
                    updateUIWithSettings(currentSettings);
                }
            });
        }
    }

    private void updateUIWithSettings(UserSettings settings) {
            switchNotifications.setChecked(settings.isNotificationsEnabled());
            switchDataSync.setChecked(settings.isDataSync());
        switchBiometric.setChecked(settings.isBiometricEnabled());
        
        // 设置SeekBar值（需要减去偏移量）
        seekBarPomodoroWork.setProgress(Math.max(0, settings.getPomodoroWorkDuration() - 5));
        tvPomodoroWork.setText(settings.getPomodoroWorkDuration() + "分钟");
        
        seekBarPomodoroBreak.setProgress(Math.max(0, settings.getPomodoroBreakDuration() - 1));
        tvPomodoroBreak.setText(settings.getPomodoroBreakDuration() + "分钟");

        // 设置主题选择
        String theme = settings.getTheme();
        int themePosition = 0;
        switch (theme) {
            case "light": themePosition = 0; break;
            case "dark": themePosition = 1; break;
            case "system": themePosition = 2; break;
        }
        spinnerTheme.setSelection(themePosition);

        // 设置同步频率
        String frequency = settings.getSyncFrequency();
        int frequencyPosition = 0;
        switch (frequency) {
            case "never": frequencyPosition = 0; break;
            case "daily": frequencyPosition = 1; break;
            case "weekly": frequencyPosition = 2; break;
            case "monthly": frequencyPosition = 3; break;
        }
        spinnerSyncFrequency.setSelection(frequencyPosition);

        // 设置数据保留时间
        String retention = settings.getDataRetention();
        int retentionPosition = 3; // 默认1年
        switch (retention) {
            case "1month": retentionPosition = 0; break;
            case "3months": retentionPosition = 1; break;
            case "6months": retentionPosition = 2; break;
            case "1year": retentionPosition = 3; break;
            case "forever": retentionPosition = 4; break;
        }
        spinnerDataRetention.setSelection(retentionPosition);

        // 设置自动锁定时间
        String autoLock = settings.getAutoLockTime();
        int lockPosition = 2; // 默认5分钟
        switch (autoLock) {
            case "immediate": lockPosition = 0; break;
            case "1min": lockPosition = 1; break;
            case "5min": lockPosition = 2; break;
            case "15min": lockPosition = 3; break;
            case "30min": lockPosition = 4; break;
            case "never": lockPosition = 5; break;
        }
        spinnerAutoLock.setSelection(lockPosition);

        // 设置API密钥（显示部分内容）
        String weatherKey = settings.getWeatherApiKey();
        if (weatherKey != null && !weatherKey.isEmpty()) {
            etWeatherApiKey.setText(maskApiKey(weatherKey));
        }
        
        String aiKey = settings.getAiApiKey();
        if (aiKey != null && !aiKey.isEmpty()) {
            etAiApiKey.setText(maskApiKey(aiKey));
        }
        
        String almanacKey = settings.getAlmanacApiKey();
        if (almanacKey != null && !almanacKey.isEmpty()) {
            etAlmanacApiKey.setText(maskApiKey(almanacKey));
        }
    }

    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.length() < 8) {
            return apiKey;
        }
        return apiKey.substring(0, 4) + "****" + apiKey.substring(apiKey.length() - 4);
    }

    private void saveSettings() {
        if (currentSettings == null) {
            Toast.makeText(requireContext(), "设置数据未加载", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新设置对象（需要加上偏移量）
        currentSettings.setNotificationsEnabled(switchNotifications.isChecked());
        currentSettings.setDataSync(switchDataSync.isChecked());
        currentSettings.setBiometricEnabled(switchBiometric.isChecked());
        currentSettings.setPomodoroWorkDuration(seekBarPomodoroWork.getProgress() + 5);
        currentSettings.setPomodoroBreakDuration(seekBarPomodoroBreak.getProgress() + 1);

        // 主题设置
        int themePosition = spinnerTheme.getSelectedItemPosition();
        String theme = "light";
        switch (themePosition) {
            case 0: theme = "light"; break;
            case 1: theme = "dark"; break;
            case 2: theme = "system"; break;
        }
        currentSettings.setTheme(theme);

        // 同步频率设置
        int frequencyPosition = spinnerSyncFrequency.getSelectedItemPosition();
        String frequency = "daily";
        switch (frequencyPosition) {
            case 0: frequency = "never"; break;
            case 1: frequency = "daily"; break;
            case 2: frequency = "weekly"; break;
            case 3: frequency = "monthly"; break;
        }
        currentSettings.setSyncFrequency(frequency);

        // 数据保留时间设置
        int retentionPosition = spinnerDataRetention.getSelectedItemPosition();
        String retention = "1year";
        switch (retentionPosition) {
            case 0: retention = "1month"; break;
            case 1: retention = "3months"; break;
            case 2: retention = "6months"; break;
            case 3: retention = "1year"; break;
            case 4: retention = "forever"; break;
        }
        currentSettings.setDataRetention(retention);

        // 自动锁定时间设置
        int lockPosition = spinnerAutoLock.getSelectedItemPosition();
        String autoLock = "5min";
        switch (lockPosition) {
            case 0: autoLock = "immediate"; break;
            case 1: autoLock = "1min"; break;
            case 2: autoLock = "5min"; break;
            case 3: autoLock = "15min"; break;
            case 4: autoLock = "30min"; break;
            case 5: autoLock = "never"; break;
        }
        currentSettings.setAutoLockTime(autoLock);

        // API密钥设置（只有在用户修改时才更新）
        String weatherKey = etWeatherApiKey.getText().toString().trim();
        if (!weatherKey.isEmpty() && !weatherKey.contains("****")) {
            currentSettings.setWeatherApiKey(weatherKey);
        }
        
        String aiKey = etAiApiKey.getText().toString().trim();
        if (!aiKey.isEmpty() && !aiKey.contains("****")) {
            currentSettings.setAiApiKey(aiKey);
        }
        
        String almanacKey = etAlmanacApiKey.getText().toString().trim();
        if (!almanacKey.isEmpty() && !almanacKey.contains("****")) {
            currentSettings.setAlmanacApiKey(almanacKey);
        }

        // 保存设置
        viewModel.saveUserSettings(currentSettings);
        Toast.makeText(requireContext(), "设置已保存", Toast.LENGTH_SHORT).show();
    }

    private void testWeatherApi() {
        String apiKey = etWeatherApiKey.getText().toString().trim();
        if (apiKey.isEmpty() || apiKey.contains("****")) {
            Toast.makeText(requireContext(), "请先输入有效的天气API密钥", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 这里可以实现实际的API测试逻辑
        Toast.makeText(requireContext(), "天气API测试功能待实现", Toast.LENGTH_SHORT).show();
    }

    private void testAiApi() {
        String apiKey = etAiApiKey.getText().toString().trim();
        if (apiKey.isEmpty() || apiKey.contains("****")) {
            Toast.makeText(requireContext(), "请先输入有效的AI助手API密钥", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 这里可以实现实际的API测试逻辑
        Toast.makeText(requireContext(), "AI助手API测试功能待实现", Toast.LENGTH_SHORT).show();
    }

    private void testAlmanacApi() {
        String apiKey = etAlmanacApiKey.getText().toString().trim();
        if (apiKey.isEmpty() || apiKey.contains("****")) {
            Toast.makeText(requireContext(), "请先输入有效的黄历API密钥", Toast.LENGTH_SHORT).show();
            return;
        }

        // 这里可以实现实际的API测试逻辑
        Toast.makeText(requireContext(), "黄历API测试功能待实现", Toast.LENGTH_SHORT).show();
    }

    private void confirmResetSettings() {
        new AlertDialog.Builder(requireContext())
                .setTitle("重置设置")
                .setMessage("确定要重置所有设置为默认值吗？")
                .setPositiveButton("确定", (dialog, which) -> resetSettings())
                .setNegativeButton("取消", null)
                .show();
    }

    private void resetSettings() {
        User currentUser = UserManager.getInstance().getCurrentUser();
        if (currentUser != null) {
            currentSettings = new UserSettings(currentUser.getId());
            updateUIWithSettings(currentSettings);
            Toast.makeText(requireContext(), "设置已重置", Toast.LENGTH_SHORT).show();
        }
    }

    private void confirmClearData() {
        new AlertDialog.Builder(requireContext())
                .setTitle("清除数据")
                .setMessage("警告：此操作将清除所有本地数据，包括任务、日记、健康记录等。此操作不可恢复！")
                .setPositiveButton("确定清除", (dialog, which) -> clearData())
                .setNegativeButton("取消", null)
                .show();
    }

    private void clearData() {
        com.example.managemyself.util.DataClearManager dataClearManager = 
                new com.example.managemyself.util.DataClearManager(requireContext());
        
        dataClearManager.clearCurrentUserData(new com.example.managemyself.util.DataClearManager.DataClearCallback() {
            @Override
            public void onSuccess() {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "所有数据已清除", Toast.LENGTH_LONG).show();
                        
                        // 数据清除后，跳转到登录页面
                        android.content.Intent intent = new android.content.Intent(getActivity(), 
                                com.example.managemyself.ui.auth.LoginActivity.class);
                        intent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK | 
                                       android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        getActivity().finish();
                    });
                }
            }
            
            @Override
            public void onError(String error) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(requireContext(), "清除数据失败: " + error, Toast.LENGTH_LONG).show();
                    });
                }
            }
        });
    }
}
